package com.weilele.mvvm.utils.proxy

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method

class CodeProxyHelper(
        private val any: Any,/*实际对象*/
        private val before: ((proxy: Any?, any: Any?/*代理示例，真正执行逻辑代码的对象*/, method: Method?/*函数*/, args: Array<out Any>?/*参数*/) -> Any?/*返回值，不是null，就代表拦截*/)? = null,
        private val after: ((call: Any?/*原函数执行后的结果*/) -> Any?/*返回值，不是null，就返回此值*/)? = null,
) : InvocationHandler {
    override fun invoke(proxy: Any?/*代理示例，真正执行逻辑代码的对象*/, method: Method?, args: Array<out Any>?): Any? {
        val beforeResult = before?.invoke(proxy, any, method, args)
        if (beforeResult != null) {
            return beforeResult
        }
        val realResult = if (args == null) {
            method?.invoke(any)
        } else {
            method?.invoke(any, *args)
        }
        val afterResult = after?.invoke(realResult)
        if (afterResult != null) {
            return afterResult
        }
        return realResult
    }
}